package com.example.dynamicdatasourcetest.datasource;

import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

@Component
public class DynamicDataSource extends AbstractRoutingDataSource {

    public DynamicDataSource(LoadDataSource loadDataSource)
    {
        Map<String, DataSource> dataSourceMap = loadDataSource.loadAllDataSource();
        super.setTargetDataSources(new HashMap<>(dataSourceMap));
        super.setDefaultTargetDataSource(dataSourceMap.get(DataSourceConst.DEFAULT_DATASOURCE));
        super.afterPropertiesSet();
    }
    @Override
    protected Object determineCurrentLookupKey() {
        return DynamicDataSourceContextHolder.getDataSourceType();
    }
}
